<?php

namespace magein\region\lib;


class Resource
{
    private $data = [];

    /**
     * Resource constructor.
     * @param $data
     * @throws \Exception
     */
    public function __construct($data)
    {
        if (empty($data)) {
            throw new \Exception('地区数据错误');
        }

        $this->data = $data;
    }


    /**
     * 创建sql文件
     * @param string $name
     * @return bool
     * @throws \Exception
     */
    public function createSql($name = 'region')
    {
        $filename = './res/region.sql';
        if (is_file($filename)) {
            unlink($filename);
        }

        $tableFilename = './res/table.sql';
        if (!is_file($tableFilename) || filesize($tableFilename) == 0) {
            throw new \Exception('表信息错误');
        }

        file_put_contents($filename, file_get_contents($tableFilename) . "\n");

        if ($this->data) {
            foreach ($this->data as $item) {
                $sql = "INSERT INTO `$name` VALUES({$item['id']},{$item['pid']} ,'{$item['name']}');" . "\n";
                file_put_contents($filename, $sql, FILE_APPEND);
            }
        }

        file_put_contents($filename, "SET FOREIGN_KEY_CHECKS=1;", FILE_APPEND);

        return true;
    }

    /**
     * 获取json数据
     * @param array $data
     * @return false|string
     */
    public function getJson($data = [])
    {
        if (empty($data)) {
            $data = $this->data;
        }

        return json_encode($data, JSON_UNESCAPED_UNICODE);
    }

    /**
     * 获取层级关系
     * @param bool $idToKey
     * @return array
     */
    public function getLevel($idToKey = true)
    {
        $data = [];
        foreach ($this->data as $item) {
            $data[$item['id']] = $item;
        }

        $result = [];

        if ($idToKey) {
            foreach ($data as $key => $item) {
                if (isset($data[$item['pid']])) {
                    $data[$item['pid']]['children'][$item['id']] = &$data[$key];
                } else {
                    $result[$item['id']] = &$data[$key];
                }
            }

            $filename = 'region-object';

        } else {
            foreach ($data as $key => $item) {
                if (isset($data[$item['pid']])) {
                    $data[$item['pid']]['children'][] = &$data[$key];
                } else {
                    $result[] = &$data[$key];
                }
            }
            $filename = 'region-array';
        }

        file_put_contents('./res/' . $filename . '.js', $this->getJson($result));

        return $result;
    }
}